<template>
    <div>
        <!-- 共用头部组件 -->
        <common-header
            headerTitle="商品详情——测试"
            :hasBack="true"
            :hasHome="true"
        ></common-header>
        <!-- 共用头部组件 -->

        <!-- 共用页面滚动组件 -->
        <common-scroll
            :scrollStyle="scrollStyle"
            :isLoadMore="false"
        >

            <!-- 店主白领标识 -->
            <img
                class="free-get-label"
                src="@/assets/images/goodsDetail/free-get-icon.png"
                v-if="goodsType == 0"
            />
            <!-- 店主白领标识 -->

            <!-- 共用轮播图组件 -->
            <common-swiper
                class="goods-swiper"
                :swiperList="swiperList"
                :swiperHeight="swiperHeight"
                :media="goodsInfo.media"
            ></common-swiper>
            <!-- 共用轮播图组件 -->

            <!-- 商品信息组件 -->
            <goods-info
                :goodsInfo="goodsInfo"
                :goodsType="goodsType"
                :userInfo="userInfo"
                @shareShow="shareShow"
            ></goods-info>
            <!-- 商品信息组件 -->

            <!-- 商品规格组件 -->
            <goods-format
                v-if="goodsType == 0"
                @selectFormat="selectFormat"
                :formatNow="formatNow"
                :goodsNum="goodsNum"
            ></goods-format>
            <!-- 商品规格组件 -->

            <!-- 商品评价组件 -->
            <goods-evaluate
                :commentList="commentList"
                :commentTotal="commentTotal"
                :goodsId="goodsId"
                :goodsType="goodsType"
            ></goods-evaluate>
            <!-- 商品评价组件 -->

            <!-- 商品详情组件 -->
            <goods-details :goodsDetail="goodsDetail"></goods-details>
            <!-- 商品详情组件 -->

        </common-scroll>

        <!-- 商品购买组件 -->
        <goods-buy
            :goodsType="goodsType"
            :goodsId="goodsId"
            :goodsNum="goodsNum"
            :userInfo="userInfo"
            :userData="userData"
            :goodsInfo='goodsInfo'
            :stock="goodsStock"
            @beVip="beVip"
            @goBindPhone="goBindPhone"
            @beMember="beMember"
        >
        </goods-buy>
        <!-- 商品购买组件 -->

        <!-- 分享引导组件 -->
        <div
            class="share-bg"
            v-if="shareTips"
            @click.prevent.self="closeShare"
        >
            <div
                class="share-main"
                ref="imageWrapper"
            >
                <slot>
                    <img
                        class="share-main-bg"
                        src="@/assets/images/goodsDetail/goods-share-bg.jpg"
                    />
                    <div class="user-info-box">
                        <img
                            class="user-img"
                            :src="'data:image/png;base64,'+headerImgUrl"
                            @load="headerImgReady"
                        />
                        <div class="user-info">
                            <div class="user-name-id">{{decodeURI(userInfo.nick_name)}} <span class="id-color">ID：{{userInfo.id}}</span></div>
                            <div class="user-tips">我已领了这款精品</div>
                        </div>
                    </div>
                    <div class="share-img-box">
                        <img
                            class="share-img"
                            :src="'data:image/png;base64,'+shareImgUrl"
                            @load="makeShareImg"
                        />
                    </div>
                    <img
                        class="share-price-bg"
                        src="@/assets/images/goodsDetail/goods-share-price.png"
                        @load="priceImgReady"
                        v-if="goodsInfo.is_upgrade<1"
                    />
                    <img
                        class="share-price-bg"
                        src="@/assets/images/goodsDetail/goods-share-price2.png"
                        @load="priceImgReady"
                        v-else
                    />
                    <div class="share-price"><span class="share-price-symbol">￥</span>{{goodsInfo.price_market/100}}</div>
                    <div class="qrcode-box">
                        <div
                            class="qrcode"
                            ref="qrCodeUrl"
                        ></div>
                    </div>
                </slot>
            </div>
            <div class="share-tips">长按图片可发送给好友一起参与~</div>
        </div>
        <!-- 分享引导组件 -->

        <!-- 绑定手机组件 -->
        <bind-phone
            :bindPhone="bindPhone"
            @closeBindPhone="closeBindPhone"
            @updateUserInfo="updateUserInfo"
        ></bind-phone>
        <!-- 绑定手机组件 -->

        <!-- 生成图片loading -->
        <div
            class="loading-bg"
            v-show="shareLoading"
        >
            <img
                class="loading-img"
                src="@/assets/images/home/loading.gif"
            />
            <div class="loading-tips">数据加载中...</div>
        </div>
        <!-- 生成图片loading -->

        <!-- 商品规格选择 -->
        <div
            class="format-select-box"
            v-show="formatShow"
            @click.prevent.self="formatShow = false"
        >
            <div class="format-select-main">
                <div class="goods-info-box">
                    <div class="goods-img-box">
                        <img
                            class="goods-img"
                            :src="formatImg"
                        />
                    </div>
                    <div class="goods-info">
                        <div class="goods-price">￥{{goodsInfo.price_0 | currency}}</div>
                        <div
                            class="goods-format-info"
                            v-if="formatNow.length>0"
                        >
                            <div
                                v-for="(item,index) of formatNow"
                                :key="index"
                            >
                                <span v-if="index>0">，</span>
                                <span>{{item}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="goods-format-box">
                    <div
                        class="goods-format-type"
                        v-for="(items,indexs) of formatList"
                        :key="indexs"
                    >
                        <div class="goods-format-title">{{items.name}}</div>
                        <div class="goods-format-list">
                            <div
                                class="goods-format-item"
                                v-for="(item,index) of items.values"
                                :key="index"
                                :class="[item.selected == 1?'selected':'',item.enable == 1?'':'unselected']"
                                @click="formatSelect(item.name,indexs,item.enable)"
                            >{{item.name}}</div>
                        </div>
                    </div>
                </div>
                <div class="goods-num-box">
                    <div class="goods-num-title">数量</div>
                    <div class="goods-num-input">
                        <div
                            class="minus"
                            @click="minus"
                        ></div>
                        <input
                            class="num-input"
                            type="tel"
                            v-model="goodsNum"
                            disabled
                        />
                        <div
                            class="add"
                            @click="add"
                        ></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 商品规格选择 -->
    </div>
</template>

<script>
import CommonHeader from '@/components/Header'
import CommonScroll from '@/components/Scroll'
import CommonSwiper from '@/components/Swiper'
import GoodsInfo from './components/GoodsInfo'
import GoodsFormat from './components/GoodsFormat'
import GoodsEvaluate from './components/GoodsEvaluate'
import GoodsDetails from './components/GoodsDetails'
import GoodsBuy from './components/GoodsBuy'
import BindPhone from '@/components/BindPhone'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import wx from 'weixin-js-sdk'
export default {
    name: 'GoodsDetail',
    components: {
        CommonHeader,
        CommonScroll,
        CommonSwiper,
        GoodsInfo,
        GoodsFormat,
        GoodsEvaluate,
        GoodsDetails,
        GoodsBuy,
        BindPhone
    },
    data() {
        return {
            scrollStyle: {
                top: '1.11rem',
                left: '0',
                right: '0',
                bottom: '1.31rem'
            },
            swiperHeight: '100%',
            swiperList: [],
            goodsInfo: '',
            goodsNum: 1,
            goodsStock: 0,
            goodsDetail: '',
            commentList: [],
            commentTotal: 0,
            userInfo: '',
            userData: '',
            goodsType: 0,
            goodsId: '',
            shareTips: false,
            bindPhone: false,
            shareImgUrl: '',
            headerImgUrl: '',
            shareLoading: false,
            headerImgIsReady: false,
            priceImgIsReady: false,
            formatShow: false,
            formatImg: '',
            formatNow: ['黄色', 'M', '清纯百合'],
            formatCopy: [],
            formatList: [
                {
                    name: '颜色',
                    values: [
                        { name: '黄色', enable: 0, selected: 0 },
                        { name: '白色', enable: 0, selected: 0 },
                        { name: '红色', enable: 0, selected: 0 }
                    ]
                },
                {
                    name: '尺码',
                    values: [
                        { name: 'S', enable: 0, selected: 0 },
                        { name: 'M', enable: 0, selected: 0 },
                        { name: 'L', enable: 0, selected: 0 },
                        { name: 'XL', enable: 0, selected: 0 }
                    ]
                },
                {
                    name: '香型',
                    values: [
                        { name: '现代的白', enable: 0, selected: 0 },
                        { name: '清纯百合', enable: 0, selected: 0 },
                        { name: '蜜桃', enable: 0, selected: 0 }
                    ]
                }
            ],
            goodsInFormat: [
                {
                    goods_id: '123',
                    attr: ['黄色', 'XL', '现代的白']
                },
                {
                    goods_id: '124',
                    attr: ['白色', 'XL', '现代的白']
                },
                {
                    goods_id: '125',
                    attr: ['黄色', 'S', '蜜桃']
                },
                {
                    goods_id: '1234',
                    attr: ['黄色', 'M', '清纯百合']
                },
                {
                    goods_id: '127',
                    attr: ['红色', 'XL', '现代的白']
                },
                {
                    goods_id: '128',
                    attr: ['红色', 'L', '蜜桃']
                },
                {
                    goods_id: '129',
                    attr: ['白色', 'M', '清纯百合']
                },
                {
                    goods_id: '129',
                    attr: ['白色', 'XL', '清纯百合']
                }
            ]
        }
    },
    mounted() {
        this.goodsType = this.$route.query.goodsType
        this.goodsId = this.$route.query.goodsId
        this.initFormat()
        this.getGoodsInfo()
        this.getUserInfo()
    },
    methods: {
        formatSelect(value, type, bool) {
            if (bool == 1) {
                this.formatNow[type] = value
                this.formatList.forEach(items => {
                    items.values.forEach(item => {
                        item.enable = 0
                        item.selected = 0
                    })
                })
                this.$nextTick(function() {
                    this.initFormat()
                })
            }
        },
        initFormat() {
            const that = this
            this.formatList.forEach((item, i) => {
                item.values.forEach((items, is) => {
                    if (
                        that.formatNow.findIndex(
                            element => element == items.name
                        ) > -1
                    ) {
                        items.selected = 1
                    }
                    that.formatCopy = JSON.parse(JSON.stringify(that.formatNow))
                    that.formatCopy[i] = items.name
                    if (
                        that.goodsInFormat.findIndex(
                            element =>
                                element.attr.toString() ==
                                that.formatCopy.toString()
                        ) > -1
                    ) {
                        items.enable = 1
                    }
                })
            })
        },
        minus() {
            if (this.goodsNum > 1) {
                this.goodsNum--
            }
        },
        add() {
            this.goodsNum++
        },
        getWxConfig() {
            const that = this
            this.axios.post('/api/jsconfig.json').then(res => {
                const data = res.data
                if (data.status == 1) {
                    let routeHost = window.location.origin
                    let routeHref = window.location.href.split('#')[0]
                    let routePath = encodeURIComponent(
                        window.location.href.split('#')[1]
                    )
                    wx.config(data.data)
                    wx.ready(function() {
                        if (typeof wx.updateAppMessageShareData == 'function') {
                            wx.updateAppMessageShareData({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareAppMessage({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                type: '', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                        if (typeof wx.onMenuShareTimeline == 'function') {
                            wx.onMenuShareTimeline({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareTimeline({
                                title:
                                    '爆款美妆免费领：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                    })
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        getGoodsInfo() {
            let postData = this.qs.stringify({
                id: this.$route.query.goodsId,
                attr_values: this.formatNowIds
            })
            this.axios.post('/api/goods/info.json', postData).then(res => {
                const data = res.data
                if (data.status == 1) {
                    this.shareLoading = false
                    this.goodsInfo = data.data
                    // this.formatList = data.data.attr_list
                    this.swiperList = data.data.imgs
                    this.goodsDetail = data.data.content
                    this.goodsStock = data.data.num
                    this.vipGoods = data.data.is_upgrade == '1'
                    this.toBase64(data.data.imgs[0].title_img, 'shareImgUrl')
                    this.getWxConfig()
                    this.goodsId = data.data.id
                    this.formatImg = data.data.imgs[0].title_img
                    this.getCommentList()
                    this.initFormat()
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        getCommentList() {
            let postData = this.qs.stringify({
                goods_id: this.goodsId,
                page_size: 5,
                page: 1
            })
            this.axios
                .post('/api/goods/comment_list.json', postData)
                .then(res => {
                    const data = res.data
                    if (data.status == 1) {
                        this.commentList = data.data.list
                        this.commentTotal = data.data.page_info.total
                    } else {
                        this.commonDialog.alert('提示', data.msg)
                    }
                })
        },
        updateUserInfo() {
            this.getUserInfo()
        },
        getUserInfo() {
            this.axios.post('/api/user/data.json').then(res => {
                const data = res.data
                if (data.status == 1) {
                    this.userData = data.data
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
            this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            if (this.userInfo.face == '') {
                this.headerImgUrl = null
                return
            } else {
                this.toBase64(this.userInfo.face, 'headerImgUrl')
            }
        },
        beVip() {
            sessionStorage.setItem(
                'cart_ids',
                JSON.stringify(this.goodsInfo.id)
            )
            sessionStorage.setItem('cart_goods', JSON.stringify(this.goodsInfo))
            sessionStorage.setItem(
                'cart_price',
                JSON.stringify(this.goodsInfo.price)
            )
            this.$router.push('/vipConfirm')
        },
        headerImgReady() {
            this.headerImgIsReady = true
        },
        priceImgReady() {
            this.priceImgIsReady = true
        },
        makeShareImg() {
            const that = this
            if (this.headerImgIsReady && this.priceImgIsReady) {
                this.toImage()
            } else {
                setTimeout(() => {
                    that.makeShareImg()
                }, 500)
            }
        },
        shareShow() {
            const that = this
            this.shareLoading = true
            this.shareTips = true
            this.$nextTick(() => {
                that.makeCode()
            })
        },
        makeCode() {
            let routeHref = window.location.href
            let qrcode = new QRCode(this.$refs.qrCodeUrl, {
                text: routeHref,
                width: 85,
                height: 85,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            })
        },
        toImage() {
            const that = this
            html2canvas(this.$refs.imageWrapper, {
                backgroundColor: null
            }).then(canvas => {
                let dataURL = canvas.toDataURL('image/png')
                document.querySelector('.share-main').innerHTML =
                    '<img width="100%" src="' + dataURL + '" />'
                setTimeout(() => {
                    that.shareLoading = false
                }, 1000)
            })
        },
        toBase64(url, target) {
            let postData = this.qs.stringify({
                url: url
            })
            this.axios.post('/api/img/base64.json', postData).then(res => {
                const data = res.data
                if (data.status == 1) {
                    this[target] = data.data
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        closeShare() {
            this.shareTips = false
            this.shareImgLoad = false
            this.sharePriceLoad = false
        },
        goBindPhone() {
            this.bindPhone = true
        },
        closeBindPhone() {
            this.bindPhone = false
        },
        beMember() {
            this.$router.push('/experience2')
        },
        selectFormat() {
            this.formatShow = true
        }
    },
    filters: {
        currency(value) {
            return parseFloat(value / 100).toFixed(2)
        }
    }
}
</script>

<style lang="stylus" scoped>
.free-get-label
    position absolute
    top 0.26rem
    right 0.4rem
    width 1.92rem
    z-index 2
.goods-swiper
    background #fff
    border-bottom 1px solid #e5e5e5
.loading-bg
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    padding 5% 10%
    background-color rgba(0, 0, 0, 0.9)
    z-index 9
    display flex
    flex-direction column
    align-items center
    justify-content center
    .loading-img
        width 1rem
        height 1rem
    .loading-tips
        width 100%
        margin-top 0.37rem
        font-size 0.38rem
        color #fff
        text-align center
.share-bg
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background-color rgba(0, 0, 0, 0.7)
    z-index 9
    display flex
    flex-direction column
    justify-content center
    align-items center
    .share-main
        position relative
        width 300px
        height 501px
        .share-img
            display block
            width 300px
            margin 0 auto
        .share-main-bg
            position absolute
            top 0
            left 0
            width 300px
            height 501px
        .user-info-box
            position absolute
            top 20px
            left 0
            right 70px
            display flex
            align-items center
            padding 0 15px
            .user-img
                width 50px
                height 50px
                border-radius 100%
            .user-info
                flex 1
                margin-left 10px
                .user-name-id
                    font-size 12px
                    color #333
                    .id-color
                        margin-left 10px
                        color #999
                .user-tips
                    margin-top 5px
                    font-size 14px
                    font-weight bold
                    color #ab2023
        .share-img-box
            position absolute
            top 80px
            left 0
            right 0
            text-align center
            .share-img
                width 270px
                height 270px
        .share-price-bg
            position absolute
            top 240px
            left 20px
            width 100px
            height 82px
        .share-price
            position absolute
            top 240px
            left 20px
            width 100px
            height 82px
            line-height 70px
            text-align center
            font-size 28px
            color #ab2023
            font-weight bold
            font-style italic
            .share-price-symbol
                font-size 13px
                margin-right 3px
        .qrcode-box
            position absolute
            bottom 35px
            right 20px
            width 85px
            height 85px
    .share-tips
        margin-top 0.37rem
        text-align center
        font-size 0.38rem
        color #fff
.format-select-box
    position absolute
    top 0
    left 0
    right 0
    bottom 1.31rem
    background-color rgba(0, 0, 0, 0.7)
    z-index 5
    .format-select-main
        position absolute
        bottom 0
        left 0
        right 0
        padding 0.45rem 0.45rem 1.33rem 0.45rem
        background #fff
        border-radius 10px 10px 0 0
        max-height 10rem
        overflow-y scroll
        .goods-info-box
            display flex
            align-items flex-end
            .goods-img-box
                width 2.24rem
                height 2.24rem
                overflow hidden
                img
                    width 100%
                    height 100%
            .goods-info
                margin-left 0.26rem
                flex 1
                .goods-price
                    font-size 0.5rem
                    color #e7463c
                .goods-format-info
                    display flex
                    margin-top 0.37rem
                    font-size 0.37rem
                    color #323232
        .goods-format-type
            margin-top 0.64rem
            .goods-format-title
                font-size 0.42rem
                color #131313
            .goods-format-list
                display flex
                flex-wrap wrap
                margin-top 0.26rem
                .goods-format-item
                    padding 0.2rem 0.4rem
                    font-size 0.34rem
                    color #131313
                    line-height 1
                    background #f6f5f5
                    border-radius 2px
                    border 1px solid #f6f5f5
                    margin-right 0.26rem
                    margin-bottom 0.26rem
                .selected
                    border-color #d7463c
                    color #d7463c
                .unselected
                    color #999
                    text-decoration line-through
        .goods-num-box
            display flex
            align-items center
            justify-content space-between
            margin-top 0.64rem
            .goods-num-title
                font-size 0.42rem
                color #131313
            .goods-num-input
                display flex
                align-items center
                width 3.2rem
                background #e5e5e5
                border-radius 2px
                .minus
                    width 1rem
                    height 0.74rem
                    background-image url('../../assets/images/goodsDetail/minus-icon.png')
                    background-size 0.24rem 0.05rem
                    background-repeat no-repeat
                    background-position center
                .add
                    width 1rem
                    height 0.74rem
                    background-image url('../../assets/images/goodsDetail/add-icon.png')
                    background-size 0.24rem 0.24rem
                    background-repeat no-repeat
                    background-position center
                .num-input
                    flex 1
                    min-width 1px
                    height 0.74rem
                    line-height 0.74rem
                    font-size 0.42rem
                    color #131313
                    text-align center
                    background #f1f1f1
</style>
